package com.czn.bookshop.web;

import com.czn.bookshop.entity.User;
import com.czn.bookshop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * 用户控制器
 *
 * @author ChenZeNan
 * @create 2020-12-27 12:45
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 注册时校验用户名
     *
     * @param username
     * @return
     */
    @RequestMapping("/checkUsername")
    @ResponseBody
    public String checkUsername(String username) {
        return userService.checkUsername(username);
    }

    /**
     * 注册用户
     *
     * @param user
     * @return
     */
    @RequestMapping("/register")
    @ResponseBody
    public String register(User user) {
        userService.save(user);
        return "success";
    }

    /**
     * 用户登录
     *
     * @param user
     * @param session
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public String login(User user, HttpSession session) {
        return userService.loginUser(user, session);
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate(); // 移除session中的对象
        return "redirect:/book/index"; //重定向到首页
    }
}
